/*******************************************************************************
 Jimm - Mobile Messaging - J2ME ICQ clone
 Copyright (C) 2003-04  Jimm Project

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ********************************************************************************
 File: src/jimm/comm/RequestInfoAction.java
 Version: ###VERSION###  Date: ###DATE###
 Author(s): Manuel Linsmayer
 *******************************************************************************/


// #sijapp cond.if protocols_ICQ is "true" #
package protocol.icq.action;


import java.io.IOException;
import java.util.Date;
import java.io.DataInputStream;
import jimm.cl.*;
import jimm.comm.*;
import jimm.*;
import protocol.icq.*;
import protocol.icq.IcqContact;
import protocol.icq.packet.*;
import jimm.modules.*;
import jimm.search.*;
import jimm.ui.*;

public class RequestInfoAction extends IcqAction {

    // Receive timeout
    private static final int TIMEOUT = 10 * 1000; // milliseconds

    /****************************************************************************/
    
    private UserInfo strData;

    // Date of init
    private long lastActivity;
    private int packetCounter;
    private IcqContact contact;

    // Constructor
    public RequestInfoAction(UserInfo data, IcqContact item) {
        super();
        packetCounter = 0;
        contact = item;
        strData = data;
        strData.uin = contact.getUserId();
    }
    public UserInfo getUserInfo() {
        return strData;
    }

    // Init action
    public void init() throws JimmException {

        // Send a CLI_METAREQINFO packet
        byte[] buf = new byte[6];
        Util stream = new Util();
        stream.writeWordLE(ToIcqSrvPacket.CLI_META_REQMOREINFO_TYPE);
        stream.writeDWordLE(Long.parseLong(strData.uin));
        sendPacket(new ToIcqSrvPacket(0, getIcq().getUserId(), ToIcqSrvPacket.CLI_META_SUBCMD, new byte[0], stream.toByteArray()));

        // Save date
        lastActivity = System.currentTimeMillis();
    }
    

    private String readAsciiz(DataInputStream stream) throws IOException {
        int len = Util.getWordLE(stream);
        if (len == 0) {
            return "";
        }
        byte[] buffer = new byte[len];
        stream.readFully(buffer);
        // TODO: check it
        return StringConvertor.byteArrayToWinString(buffer); 
    }

    
    // Forwards received packet, returns true if packet was consumed
    public boolean forward(Packet packet) throws JimmException {
        boolean consumed = false; 

        // Watch out for SRV_FROMICQSRV packet
        if (packet instanceof FromIcqSrvPacket) {
            FromIcqSrvPacket fromIcqSrvPacket = (FromIcqSrvPacket) packet;

            // Watch out for SRV_META packet
            if (fromIcqSrvPacket.getSubcommand() != FromIcqSrvPacket.SRV_META_SUBCMD) {
                return false;
            }
            
            // Get packet data
            DataInputStream stream = Util.getDataInputStream(fromIcqSrvPacket.getData(), 0);
            
            // Watch out for SRV_METAGENERAL packet
            try {
                int type = Util.getWordLE(stream);
                stream.readByte(); // Success byte
                switch (type) {
                case FromIcqSrvPacket.SRV_META_GENERAL_TYPE: //  basic user information
                    {
                        strData.nick        = readAsciiz(stream); // nickname
                        strData.firstName   = readAsciiz(stream);
                        strData.lastName    = readAsciiz(stream);
                        strData.email       = readAsciiz(stream); // email
                        strData.homeCity    = readAsciiz(stream); // home city
                        strData.homeState   = readAsciiz(stream); // home state
                        strData.homePhones  = readAsciiz(stream); // home phone
                        strData.homeFax     = readAsciiz(stream); // home fax
                        strData.homeAddress = readAsciiz(stream); // home address
                        strData.cellPhone   = readAsciiz(stream); // cell phone
                        packetCounter++;
                        consumed = true;
                        break;
                    }
                    
                case 0x00DC: // more user information
                    {
                        strData.age = Util.getWordLE(stream);
                        strData.gender = stream.readByte();
                        strData.homePage = readAsciiz(stream);
                        int year = Util.getWordLE(stream);
                        int mon  = stream.readByte();
                        int day  = stream.readByte();
                        strData.birthDay = (year != 0)
                                ? (day + "." + (mon < 10 ? "0" : "") + mon + "." + year)
                                : null;
                        packetCounter++;
                        consumed = true;
                        break;
                    }
                        
                case 0x00D2: // work user information
                    {
                        strData.workCity    = readAsciiz(stream);
                        strData.workState   = readAsciiz(stream);
                        strData.workPhone   = readAsciiz(stream);
                        strData.workFax     = readAsciiz(stream);
                        strData.workAddress = readAsciiz(stream);

                        readAsciiz(stream);                          // work zip code
                        Util.getWordLE(stream);                      // work country code
                        strData.workCompany    = readAsciiz(stream); // work company
                        strData.workDepartment = readAsciiz(stream); // work department
                        strData.workPosition   = readAsciiz(stream); // work position
                        packetCounter++;
                        consumed = true;
                        break;
                    }
                        
                case 0x00E6: // user about information
                    {
                        strData.about = readAsciiz(stream); // notes string
                        packetCounter++;
                        consumed = true;
                        break;
                    }
                        
                case 0x00F0: // user interests information
                    {
                        StringBuffer sb = new StringBuffer();
                        int counter = stream.readByte();
                        for (int i = 0; i < counter; ++i) {
                            Util.getWordLE(stream);
                            String item = readAsciiz(stream).trim();
                            if (item.length() == 0) continue;
                            if (sb.length() != 0) sb.append(", ");
                            sb.append(item);
                        }
                        strData.interests = sb.toString();
                        packetCounter++;
                        consumed = true;
                        break;
                    }
                }
            
            } catch (Exception e) {
                // #sijapp cond.if modules_DEBUGLOG is "true" #
                DebugLog.println("Request Info action " + e.getMessage() + " (" + e.getClass().toString() + ")");
                // #sijapp cond.end#
            }
            
            // is completed?
            strData.setOptimalName();
            strData.updateProfileView();
        }

        return consumed;
    }

    // Returns true if the action is completed
    public boolean isCompleted() {
        return packetCounter >= 5;
    }


    // Returns true if an error has occured
    public boolean isError() {
        return (lastActivity + TIMEOUT < System.currentTimeMillis());
    }


}
// #sijapp cond.end #
